package cn.detu._05mvcboot02.controller;

import cn.detu._05mvcboot02.common.response.JsonResult;
import cn.detu._05mvcboot02.mapper.UserMapper;
import cn.detu._05mvcboot02.pojo.dto.UserDTO;
import cn.detu._05mvcboot02.pojo.entity.User;
import cn.detu._05mvcboot02.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /*
    *  如果没有添加 @RequestBody 注解
    *  默认使用form表单的方式接收数据
    * */
//    1.添加用户功能
    @ApiOperation("用户登录")
    @PostMapping(value = "insert")
    public JsonResult addUser(@RequestBody UserDTO userDTO , @ApiIgnore HttpSession session){
        log.debug("userDTO = " + userDTO + ", session = " + session);

         /*
            梳理业务逻辑,确定接口,以注册功能为例:
            1.接收客户端传递过来的数据;
            2.校验数据的合法性;
            3.确认用户名是否被占用[SELECT接口];
              3.1 被占用,return返回结束;
              3.2 未被占用,插入数据[INSERT接口];
              3.3 返回响应.
         */

        User user = new User();
//        复制属性
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());

        log.debug("user = "+user);
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @ApiOperation("显示用户列表")
    @GetMapping("userList")
    public JsonResult userList(){
        System.out.println(userMapper.selectUserList());
        List<UserListVO> userListVOS = userMapper.selectUserList();
        return JsonResult.ok(userListVOS);
    }

//    3.删除指定用户
    @ApiOperation("删除指定用户")
    @DeleteMapping("delete")
    @ApiImplicitParam(name="id",value = "用户的Id",required = true)
    public JsonResult deleteUser(Long id){
        userMapper.deleteUser(id);

        return JsonResult.ok();
    }

    //    更新指定用户
    @ApiOperation("更新指定用户")
    @PutMapping("update")
    public JsonResult updateUser(User user){
        userMapper.updateUser(user);
        return JsonResult.ok();
    }

    /*
    * 5.根据用户ID查询指定用户信息
    * */
    @ApiOperation("根据用户ID查询用户基本信息")
    @GetMapping("{id}")
    @ApiImplicitParam(name = "id",value = "用户ID",required = true)
    public JsonResult getUserById(@PathVariable("id") int id){

        return JsonResult.ok(userMapper.selectUserById(id));
    }

}
